import json

from passlib.context import CryptContext
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql.sqltypes import String, Integer

from utils.db import BaseModel

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


class UserModel(BaseModel):
    """用户模型"""
    __tablename__ = 'user'
    __table_args__ = {'extend_existing': True, 'comment': "用户表"}

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True, comment="主键id")
    name: Mapped[str] = mapped_column(String(255), unique=True, comment="用户名")
    password: Mapped[str] = mapped_column(String(255), comment="密码")

    @staticmethod
    def verify_password(plain_password: str, hashed_password: str):
        """
        验证密码
        :param plain_password: 密码原文
        :param hashed_password: 哈希后的密码
        :return: 是否一致
        """
        return pwd_context.verify(plain_password, hashed_password)

    @staticmethod
    def get_password_hash(password: str):
        """
        加密密码
        :param password: 原文密码
        :return: 哈希后的密码
        """
        return pwd_context.hash(password)

    def to_dict(self):
        return {
            "id": self.id,
            "name": self.name,
            "password": self.password,
            "create_at": self.create_at.strftime("%Y-%m-%d %H:%M:%S"),
            "update_at": self.update_at.strftime("%Y-%m-%d %H:%M:%S"),
        }

    def __str__(self):
        return json.dumps(self.to_dict(), ensure_ascii=False)
